package com.example.demo.controller;

import com.example.demo.entity.Prize;
import com.example.demo.service.PrizeService;
import com.example.demo.utils.Lotteryutil_New;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/prize")
public class PrizeController {
    @Resource
    private PrizeService prizeService;


    @RequestMapping("/getAllPrize")
    @ResponseBody
    public List<Prize> getAllPrize(){
        List<Prize> prizeList = prizeService.getAllPrize();
        return prizeList;
    }

    /**
     * 抽奖
     * @return
     */
    @RequestMapping("/lucky")
    @ResponseBody
    public Map lucky(HttpSession session){

        Map map = new HashMap();

        List<Prize> gifts = prizeService.getAllPrize();
        Boolean flag=false;
        for(int i=0;i<gifts.size();i++){
            if(gifts.get(i).getLuckyCount()!=0){
                flag=true;
            }
        }
        if(flag){
            List<Double> orignalRates = Lotteryutil_New.addProbability(gifts);
            int orignalIndex = Lotteryutil_New.lottery(orignalRates);
            Prize result = gifts.get(orignalIndex);
            result.setLuckyCount(result.getLuckyCount()-1);
            //修改奖品表库存
            prizeService.updatePrizeCount(result);
            map.put("msg",1);
            map.put("result",result);
        } else {
            map.put("msg",2);
        }


        return map;
    }

    @RequestMapping("/getPrizeById")
    @ResponseBody
    public Prize getPrizeById(Integer prizeId){
        Prize prize = prizeService.getPrizeById(prizeId);
        return prize;
    }

    @RequestMapping("/back405")
    public String back405(){
        return "405";
    }
}
